<template>
    <el-select class="w-full" :size="size" v-model="val" :remote-method="(query: string) => remoteMethod(query, item)"
        :loading="loading" :filterable="item?.filterable" :remote="item?.remote" :placeholder="item.placeholder || '请选择'"
        :clearable="item?.extra?.clearable ?? true" :multiple="item.multiple" :disabled="item.disabled"
        @change="item?.callbacks?.handleChange"
        @focus="item?.callbacks?.handleFocus">
        <el-option v-for="(i) in item?.options" :key="i[(item.defaultAttrs as DefaultAttrsDto)?.value || 'value']"
            :label="i[(item.defaultAttrs as DefaultAttrsDto)?.label || 'label']"
            :value="i[(item.defaultAttrs as DefaultAttrsDto)?.value || 'value']"></el-option>
    </el-select>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import type { PropType } from 'vue'
import type { FormItemDto, DefaultAttrsDto } from '@/components/form-component/type'

const props = defineProps({
    value: {
        type: [String, Number, Array] as PropType<string | number | Array<string | number>>,
    },
    size: {
        type: String as PropType<'large' | 'default' | 'small'>,
        default: 'default'
    },
    item: {
        type: Object as PropType<FormItemDto>,
        required: true
    }
})

const emits = defineEmits(['update:value', 'change'])

const val = ref()

const loading = ref(false)

let timer = 0
const remoteMethod = async (query: string, item: FormItemDto) => {
    if (timer) clearTimeout(timer)
    timer = window.setTimeout(async () => {
        if (item?.callbacks?.remoteMethod) {
            loading.value = true
            await item.callbacks.remoteMethod(query)
            loading.value = false
        }
    }, 300)
}

watch(() => props.value, (newval) => {
    val.value = newval
}, {
    immediate: true
})

watch(val, (newval) => {
    emits('update:value', newval)
}, {
    deep: true
})

</script>
<style lang="scss" scoped></style>
